package com.jie.server.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jie.common.annotation.DataScope;
import com.jie.common.constant.UserConstants;
import com.jie.common.utils.StringUtils;
import com.jie.server.modules.system.entity.Role;
import com.jie.server.modules.system.entity.User;
import com.jie.server.modules.system.entity.UserRole;
import com.jie.server.modules.system.excel.UserExcel;
import com.jie.server.modules.system.mapper.RoleMapper;
import com.jie.server.modules.system.mapper.UserMapper;
import com.jie.server.modules.system.service.IUserRoleService;
import com.jie.server.modules.system.service.IUserService;
import com.jie.server.modules.system.vo.RoleUserResultVo;
import com.jie.server.modules.system.vo.UserQueryVo;
import com.jie.server.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 用户表 服务实现类
 * @author: xiaojie
 * @since: 2024/12/13 0013
 */
@Slf4j
@Service
public class UserSeviceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private RoleMapper roleMapper;



    /**
     * 注册功能
     * @param user
     * @return XlUser
     */
    @Override
    public User register(User user) {
        User newUser = new User();
        BeanUtils.copyProperties(user, newUser);
        // 判断账号是否存在
        int usercount = baseMapper.checkUserNameUnique(newUser.getUserCode());
        if (usercount > 0) {
            return null;
        }
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(user.getPassWord());
        newUser.setPassWord(encodePassword);
        this.baseMapper.insert(newUser);
        return newUser;
    }

    /**
     * 查询用户
     * @param userCode
     * @return XlUser
     */
    @Override
    public User getUserByCode(String userCode) {
        List<User> users = baseMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getUserCode,userCode));
        if (CollectionUtil.isNotEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    /**
     * 通过用户名查询用户
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByUserName(String userName) {
        return baseMapper.selectUserByUserName(userName);
    }

    /**
     * 获取列表。分页
     * @param queryVo 查询参数
     * @return page
     */
    @Override
    public Page<User> listMemberPage(UserQueryVo queryVo) {
        Page<User> page = new Page<>(queryVo.getCurrentPage(),queryVo.getPageSize());
        List<User> list = baseMapper.selectUserList(queryVo,page);
        page.setRecords(list);
        return page;
    }

    /**
     * 校验用户名称是否唯一
     * @param userCode 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userCode) {
        //查询是否有相同用户名的用户
        int usercount = baseMapper.checkUserNameUnique(userCode);
        if (usercount > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 添加用户
     * @param user
     * @return boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean create(User user) {
        //将密码进行加密操作
        String encodePassword = passwordEncoder.encode(user.getPassWord());
        user.setPassWord(encodePassword);
        boolean flag = save(user);
        if (flag) {
            //新增用户角色信息
            flag = insertUserRole(user);
        }
        return flag;
    }

    /**
     * 修改用户
     * @param user
     * @return boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(User user) {
        boolean flag = updateById(user);
        if (flag) {
            //删除用户角色信息
            userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, user.getUserId()));
            //新增用户角色信息
            flag = insertUserRole(user);
        }
        return flag;
    }

    /**
     * 批量删除用户
     * @param ids
     * @return boolean
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(List<Long> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {
            boolean flag = this.removeBatchByIds(ids);
            if (flag) {
                // 删除用户角色表
                flag = userRoleService.remove(new LambdaQueryWrapper<UserRole>().in(UserRole::getUserId,ids));
                return flag;
            }
        }
        return true;
    }

    /**
     * 通过用户ID查询用户
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public User selectUserById(Long userId) {
        return baseMapper.selectUserById(userId);
    }

    /**
     * 根据用户ID查询用户所属角色组
     * @param userId 用户id
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId) {
        List<Role> list = roleMapper.selectRolePermissionByUserId(userId);
        if (CollectionUtil.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(Role::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 修改用户头像
     * @param userId 用户id
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(Long userId, String avatar) {
        User user = getById(userId);
        if (user != null) {
            user.setAvatar(avatar);
            return updateById(user);
        }
        return false;
    }

    /**
     * 新增用户角色信息
     * @param user 用户对象
     */
    public boolean insertUserRole(User user) {
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            // 新增用户与角色管理
            List<UserRole> list = new ArrayList<UserRole>(user.getRoleIds().length);
            for (Long roleId : user.getRoleIds()) {
                UserRole ur = new UserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            return userRoleService.saveBatch(list);
        }
        return true;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RoleUserResultVo> selectAllocatedList(User user) {
        return baseMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<RoleUserResultVo> selectUnallocatedList(User user) {
        return baseMapper.selectUnallocatedList(user);
    }

    @Override
    public void export(HttpServletResponse response) {
        // 查询所有用户
        List<User> list = baseMapper.selectList(null);
        // 转换数据
        List<UserExcel> excelList = list.stream().map(item ->
                {
                    UserExcel user = new UserExcel();
                    user.setUserCode(item.getUserCode());
                    user.setRealName(item.getRealName());
                    user.setUserType(item.getUserType() == 1 ?"admin":"会员");
                    user.setUserEmail(item.getUserEmail());
                    user.setPassWord(item.getPassWord());
                    user.setUserNickname(item.getUserNickname());

                    return user;
                })
                .collect(Collectors.toList());
        // 调用工具类导出
        ExcelUtil.exportExcel("用户数据","用户",excelList,UserExcel.class,response);

    }

}
